package com.sunxd.zookeeper.use.lock;

import com.sunxd.zookeeper.use.ZkConf;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.*;
import org.springframework.stereotype.Component;

/**
 * @author: 作者名称
 * @date: 2021-07-05 15:23
 **/
@Component
@Slf4j
public class ZkLockUtil {

    private final ZkConf zkConf;

    public ZkLockUtil(ZkConf zkConf) {
        this.zkConf = zkConf;
    }

    // 全异步执行
    public void excute(String path, String data) {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                ZooKeeper zookeeper = zkConf.getZookeeper(path);
                ZkLockWatcher zkLockWatcher = new ZkLockWatcher();
                zkLockWatcher.setZookeeper(zookeeper);
                zkLockWatcher.setPath(path);
                zkLockWatcher.setDate(data );
                zkLockWatcher.setThreadName(Thread.currentThread().getName());
                try {
                    log.info(" 线程：{} 开始处理业务：ephemeralPath：{}",zkLockWatcher.getThreadName());
                    zkLockWatcher.tryLock();
//                    Thread.sleep(2000);
                    zkLockWatcher.unlock();
                    log.info(" 线程：{} 业务处理完成：ephemeralPath：{}",zkLockWatcher.getThreadName());
                } catch (Exception e) {
                    log.info("---zk create ephemeral error ,path:{} , bytes:{} ,e:{} ", path, data,e);
                }
            }).start();
        }

        while (true) {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
